package com.acxiom.foodreview.controller.web;

import javax.servlet.http.HttpSession;

import org.apache.log4j.Logger;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.authentication.AnonymousAuthenticationToken;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

/**
 * Created by hadong on 2017-03-23. ExamplesController
 */

@Controller
public class IndexController {

	private Logger log = Logger.getLogger(IndexController.class);

	@RequestMapping("")
	public String index(Model model) {
		Authentication auth = SecurityContextHolder.getContext().getAuthentication();
		String name = "游客";
		if (!(auth instanceof AnonymousAuthenticationToken)) {
			UserDetails userDetails = (UserDetails) auth.getPrincipal();
			name = userDetails.getUsername();
		}
		model.addAttribute("name", name);
		log.info("index");
		return "index/index";
	}

	@RequestMapping("login")
	public String login(@RequestParam(value = "error", required = false) String error, @RequestParam(value = "logout", required = false) String logout, Model model, HttpSession httpSession) {
		String message = null;
		if (null != error) {
			Exception exception = (Exception) httpSession.getAttribute("SPRING_SECURITY_LAST_EXCEPTION");
			message = "未知错误: ".concat(exception.getMessage());
			if (exception instanceof BadCredentialsException) {
				message = "用户名或者密码错误！";
			}
		}
		if (null != logout) {
			model.addAttribute("message", "您已登出成功！");
		}
		model.addAttribute("message", message);
		return "index/login";
	}

	@RequestMapping("expired")
	@ResponseBody
	public String expired() {
		return "expired";
	}
	
	@RequestMapping("accessDenied")
	@ResponseBody
	public String accessDenied() {
		return "accessDenied";
	}

	@RequestMapping("admin")
	@PreAuthorize("hasRole('ROLE_ADMIN')")
	@ResponseBody
	public String admin(Model model) {
		return "admin page";
	}

}
